package org.example.Server.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.example.Server.mapper.semester.SemesterMapper;
import org.example.Server.mapper.unit.UnitMapper;
import org.example.Server.model.BaiduAgentRequest;
import org.example.Server.model.question.QsAiDTO;
import org.example.Server.model.question.QsHeader;
import org.example.Server.model.question.Question;
import org.example.Server.model.semester.SemAIDTO;
import org.example.Server.model.semester.SemAIIntro;
import org.example.Server.model.unit.UnitVO;
import org.example.Server.utils.JwtUtils;
import org.example.Server.utils.ResultAPI;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/youxich/agent")
public class StreamController {
    @Autowired
    SemesterMapper semesterMapper;
    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .addInterceptor(new RetryInterceptor(3, 1000)) // 最多重试3次，每次间隔1秒
            .build();
    @Autowired
    UnitMapper unitMapper;
    // 问答板块
    final String appAnsId = "YTk2ejbUc1TDsr0Q28WbpDBM3P6TtOdG";
    final String secretAnsKey = "VF9BaoswFxgbi1oA3cFLKIShRZg4mqgm";
    // 创建试题
    final String appQsId = "Sjmjmi5cj3e8BJtQ2crv3LWaSQuIKxPx";
    final String secretQsKey = "tZAZyYHKp0u18VHagcXrQoVwbiOmFNIg";

    // 获取摘要
    final String appIntroId = "noNngin56c1mVn54hOnoT3BpYah7QY9I";
    final String secretIntroKey = "wsLXFFLfuvseYEUPiLJLPz7Z2TXeb3pJ";

    /**
     * 智能问答
     *
     * @param semAIDTO
     * @return
     */
    @PostMapping(path = "/answer", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter proxyBaiduStream(@RequestBody SemAIDTO semAIDTO) {
        String chatRequest = semAIDTO.getChatRequest();
        log.info("智能问答chatRequest:{}", chatRequest);
        String userId = String.valueOf(semAIDTO.getUser_id());
        SseEmitter emitter = new SseEmitter(10000L); // 超时时间60秒

        // 1. 创建OkHttpClient
//        OkHttpClient client = new OkHttpClient.Builder()
//                .connectTimeout(30, TimeUnit.SECONDS)
//                .readTimeout(60, TimeUnit.SECONDS) // 长连接需要更长的读取超时
//                .writeTimeout(30, TimeUnit.SECONDS)
//                .build();

        // 2. 构建请求URL和请求体
        String url = "https://agentapi.baidu.com/assistant/conversation?appId=" + appAnsId + "&secretKey=" + secretAnsKey;

        BaiduAgentRequest baiduAgentRequest = BaiduAgentRequest.setBaiduAgentRequest(chatRequest, userId);
        baiduAgentRequest.setSource(appAnsId);
        String requestBody = JSONObject.toJSONString(baiduAgentRequest);

        Request request = new Request.Builder()
                .url(url)
                .post(okhttp3.RequestBody.create(requestBody, okhttp3.MediaType.parse("application/json")))
                .addHeader("Content-Type", "application/json")
                .build();
        log.info("智能问答requestBody:{}", requestBody);
        // 3. 异步执行SSE数据转发
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                emitter.completeWithError(e);
                log.info("智能问答onFailure:{}", e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                    emitter.completeWithError(new IOException("Unexpected code " + response));
                    log.info("智能问答>>!response.isSuccessful()");
                    return;
                }

                try (response; okhttp3.ResponseBody body = response.body();
                     BufferedReader reader = new BufferedReader(new InputStreamReader(body.byteStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("data:")) {
                            // 透传SSE数据块
                            emitter.send(line.replace("data:", "").trim().getBytes(StandardCharsets.UTF_8));
                            log.info(line);
                        }
                    }
                    emitter.complete();
                } catch (Exception e) {
                    emitter.completeWithError(e);
                    log.error("出问题了》》{}", e.getMessage());
                }
                // 确保始终关闭响应
            }
        });

        return emitter;
    }


    /**
     * AI创造题目
     *
     * @param qsAiDTO
     * @return
     * @throws IOException
     */
    @PostMapping("/qs")
    public ResultAPI createQs(@RequestBody QsAiDTO qsAiDTO) throws IOException {
        String userId = String.valueOf(qsAiDTO.getUser_id());
        Gson gson = new Gson();
        String json = gson.toJson(qsAiDTO);
        log.info(json);

        // 1. 创建OkHttpClient（建议作为类成员变量复用）
//        OkHttpClient client = new OkHttpClient.Builder()
//                .connectTimeout(30, TimeUnit.SECONDS)
//                .readTimeout(30, TimeUnit.SECONDS)
//                .writeTimeout(30, TimeUnit.SECONDS)
//                .build();

        try {
            // 2. 构建请求URL
            String url = "https://agentapi.baidu.com/assistant/getAnswer?appId=" + appQsId + "&secretKey=" + secretQsKey;

            // 3. 构建请求体
            BaiduAgentRequest request = BaiduAgentRequest.setBaiduAgentRequest(json, userId);
            request.setSource(appQsId);
            String requestJson = JSON.toJSONString(request);

            okhttp3.RequestBody body = okhttp3.RequestBody.create(
                    requestJson,
                    okhttp3.MediaType.parse("application/json; charset=utf-8")
            );

            // 4. 构建请求
            Request httpRequest = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            // 5. 发送请求并获取响应
            // 定义重试配置
            int maxRetries = 3;
            int retryDelayMillis = 1000; // 每次重试间隔1秒
            String res = "";
            for (int attempt = 1; attempt <= maxRetries; attempt++) {
                try (Response response = client.newCall(httpRequest).execute()) {
                    if (!response.isSuccessful()) {
                        log.error("请求失败，状态码: {}, 尝试次数: {}", response.code(), attempt);
                        if (attempt == maxRetries) {
                            return ResultAPI.error("请求服务端发生异常，请稍后重试");
                        }
                    } else {
                        res = response.body().string();
                        log.info("响应内容: {}", res);

                        // 解析JSON并检查data是否为空
                        ObjectMapper mapper = new ObjectMapper();
                        JsonNode rootNode = mapper.readTree(res);

                        // 检查status是否为0且data是否为空
                        if (rootNode.path("status").asInt() == 0 && rootNode.path("data").isNull()) {
                            log.warn("获取到空数据，尝试重试 ({} of {})", attempt, maxRetries);
                            if (attempt == maxRetries) {
                                return ResultAPI.error("AI正在加载....");
                            }
                        } else {
                            // 数据正常，继续处理
                            break;
                        }
                    }
                } catch (Exception e) {
                    log.error("请求异常，尝试次数: {}，错误: {}", attempt, e.getMessage());
                    if (attempt == maxRetries) {
                        return ResultAPI.error("请求服务端发生异常，请稍后重试");
                    }
                }
                // 等待指定时间后重试
                Thread.sleep((long) retryDelayMillis * attempt); // 指数退避策略，每次重试间隔递增
            }

            // 6. 解析JSON响应
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(res);

            // 7. 提取目标字段
            String aiResponse;
            try {
                aiResponse = rootNode
                        .path("data")
                        .path("content")
                        .get(0)
                        .path("data")
                        .asText();
            } catch (Exception e) {
                return ResultAPI.error("AI正在加载....");
            }

            // 8. 处理响应数据
            String trimRe = aiResponse.replace("```json", "").replace("```", "").trim();
            System.out.println(trimRe);
            Question qs = gson.fromJson(trimRe, Question.class);
            return ResultAPI.success(qs);

        } catch (Exception e) {
            log.error("请求发生异常", e);
            return ResultAPI.error("请求服务端发生异常，请稍后重试");
        }
    }

    @PostMapping("/intro")
    public ResultAPI getIntro(@RequestBody SemAIIntro semAIIntro) throws IOException {
        log.info("start getIntro{}", semAIIntro);
        String userId = String.valueOf(semAIIntro.getUser_id());
        Integer semId = semAIIntro.getSem_id();
//        Gson gson = new Gson();
//        List<UnitVO> data = unitMapper.getUnitsBySemId(semId);
//        log.info("UnitVO:{}", data);
//        String json = gson.toJson(data);
//        log.info(json);
//
//        try {
//            String url = "https://agentapi.baidu.com/assistant/getAnswer?appId=" + appIntroId + "&secretKey=" + secretIntroKey;
//
//            BaiduAgentRequest request = BaiduAgentRequest.setBaiduAgentRequest(json, userId);
//            request.setSource(appIntroId);
//            String requestJson = JSON.toJSONString(request);
//
//            // 修正后的RequestBody创建方式
//            okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json; charset=utf-8");
//            okhttp3.RequestBody body = okhttp3.RequestBody.create(
//                    requestJson,
//                    mediaType
//            );
//
//            Request httpRequest = new Request.Builder()
//                    .url(url)
//                    .post(body)
//                    .addHeader("Content-Type", "application/json")
//                    .build();
//
//            String res = "";
//            try (Response response = client.newCall(httpRequest).execute()) {
//                if (!response.isSuccessful()) {
//                    log.error("请求失败，状态码: {}", response.code());
//                    return ResultAPI.error("请求服务端发生异常，请稍后重试");
//                }
//                res = response.body().string();
//                log.info(res);
//            }
//
//            ObjectMapper mapper = new ObjectMapper();
//            JsonNode rootNode = mapper.readTree(res);
//
//            String aiResponse = "";
//            try {
//                aiResponse = rootNode
//                        .path("data")
//                        .path("content")
//                        .get(0)
//                        .path("data")
//                        .asText();
//            } catch (Exception e) {
//                return ResultAPI.error("AI正在加载....");
//            }
//
//            String rep = aiResponse.replace("```json", "").replace("```", "").trim();
//            return ResultAPI.success(rep);
//
//        } catch (Exception e) {
//            log.error("请求发生异常", e);
//            return ResultAPI.error("请求服务端发生异常，请稍后重试");
//        }
        String intro = semesterMapper.getIntro(semId);
        return ResultAPI.success(intro);
    }
}

